/*
 * #%L
 * SwiftUIWeb Maven Webapp
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.linkwithweb.products.swiftui.controller;

import java.text.ParseException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.plexus.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.linkwithweb.products.swiftui.dataobject.FrameworkEvent;
import com.linkwithweb.products.swiftui.dataobject.FrameworkEventScheduler;
import com.linkwithweb.products.swiftui.model.EventResponse;
import com.linkwithweb.products.swiftui.model.EventScheduler;
import com.linkwithweb.products.swiftui.service.PlatformService;
import com.linkwithweb.products.swiftui.spring.jdbc.MapObject;
import com.linkwithweb.products.swiftui.utils.DateUtils;

import edu.emory.mathcs.backport.java.util.Arrays;

/**
 * @author ashwin kumar
 * 
 */
@Controller
public class EventSchedulerController extends AbstractController {
	@Autowired
	@Qualifier("platformService")
	private PlatformService platformService;

	/**
	 * Constructor
	 */
	public EventSchedulerController() {
	}

	@RequestMapping("/scheduler/events/eventscheduler")
	public ModelAndView buildScheduler(@RequestParam(value = "schedulerId", required = false) String schedulerId,
			HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		EventScheduler eventScheduler = new EventScheduler();
		eventScheduler.setSchedulerId(schedulerId);

		FrameworkEventScheduler frameworkEventScheduler = getPlatformService().loadEventScheduler(schedulerId);
		eventScheduler.setSchedulerName(frameworkEventScheduler.getSchedulerName());
		eventScheduler.setSearchOptions(Arrays.asList(frameworkEventScheduler.getSearchByColumns().split(",")));
		/**
		 * Get the Resource ID based on Framework Event scheduler....
		 */
		List<MapObject> resourceList = getPlatformService().getResourcesForScheduler(frameworkEventScheduler,
				Collections.EMPTY_MAP);

		eventScheduler.setResourceList(resourceList);
		paramMap.put("scheduler", eventScheduler);
		// paramMap.put("eventList",
		// getPlatformService().loadEvents(schedulerId));
		return new ModelAndView("eventscheduler/event_scheduler", paramMap);
	}

	@RequestMapping("/scheduler/events/sections")
	public ModelAndView getSections(@RequestParam(value = "schedulerId", required = false) String schedulerId,
			HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		EventScheduler eventScheduler = new EventScheduler();
		eventScheduler.setSchedulerId(schedulerId);

		FrameworkEventScheduler frameworkEventScheduler = getPlatformService().loadEventScheduler(schedulerId);
		eventScheduler.setSchedulerName(frameworkEventScheduler.getSchedulerName());
		eventScheduler.setSearchOptions(Arrays.asList(frameworkEventScheduler.getSearchByColumns().split(",")));
		/**
		 * Get the Resource ID based on Framework Event scheduler....
		 */
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("offset", httpServletRequest.getParameter("offset"));
		String offset = httpServletRequest.getParameter("offset");
		int offsetNumber = 0;
		if(StringUtils.isNotBlank(offset)){
			offsetNumber = Integer.parseInt(offset);
		}
		if(StringUtils.equalsIgnoreCase(httpServletRequest.getParameter("user_action"), "next")){
			offsetNumber = offsetNumber + 5;
		}else if(StringUtils.equalsIgnoreCase(httpServletRequest.getParameter("user_action"), "previous")){
			offsetNumber = offsetNumber - 5;
		}
		
		if(offsetNumber < 0){
			offsetNumber = 0;
		}
		
		offset  = String.valueOf(offsetNumber);

		params.put(httpServletRequest.getParameter("Search1") + httpServletRequest.getParameter("Operator1"),
				httpServletRequest.getParameter("value1"));

		params.put(httpServletRequest.getParameter("Search2") + httpServletRequest.getParameter("Operator2"),
				httpServletRequest.getParameter("value2"));
		params.put("offset",offset);

		List<MapObject> resourceList = getPlatformService().getResourcesForScheduler(frameworkEventScheduler, params);

		eventScheduler.setResourceList(resourceList);
		paramMap.put("scheduler", eventScheduler);
		paramMap.put("user_action", httpServletRequest.getParameter("user_action"));

		// paramMap.put("eventList",
		// getPlatformService().loadEvents(schedulerId));
		return new ModelAndView("eventscheduler/sections", paramMap);
	}

	/**
	 * @param gridName
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @return
	 */
	@RequestMapping("/scheduler/events/list")
	public ModelAndView listEvents(@RequestParam(value = "schedulerId", required = false) String schedulerId,
			HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
		Map<String, Object> paramMap = new HashMap<String, Object>();

		Map<String, String> arguments = new HashMap<String, String>();
		arguments.put("sections", httpServletRequest.getParameter("sections"));
		
		paramMap.put("eventList", getPlatformService().loadEvents(schedulerId, arguments));
		
		
		return new ModelAndView("eventscheduler/events", paramMap);
	}

	/**
	 * @param gridName
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @return
	 */
	@RequestMapping("/scheduler/events/action")
	public ModelAndView addEvent(@RequestParam(value = "schedulerId", required = false) String schedulerId,
			HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
		Map<String, Object> paramMap = new HashMap<String, Object>();

		String ids = httpServletRequest.getParameter("ids");
		String id = httpServletRequest.getParameter(ids + "_id");
		String editing = httpServletRequest.getParameter("editing");
		String action = httpServletRequest.getParameter(ids + "_!nativeeditor_status");
		String start_date_string = httpServletRequest.getParameter(ids + "_start_date");
		String end_date_string = httpServletRequest.getParameter(ids + "_end_date");
		String text = httpServletRequest.getParameter(ids + "_text");
		String resource_id = httpServletRequest.getParameter(ids + "_resource_id");
		FrameworkEvent event = new FrameworkEvent();
		event.setSchedulerId(schedulerId);
		EventResponse eventResponse = new EventResponse();
		if (StringUtils.equalsIgnoreCase("inserted", action)) {
			event.setUniqueKey(0);
			event.setEventId("ID_" + System.nanoTime());
			event.setEventLatitude(null);
			event.setEventName("ID_" + System.nanoTime());
			try {
				event.setEventStartDate(DateUtils.getInstance().getDate(start_date_string, "yyyy-MM-dd hh:mm"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				event.setEventEndDate(DateUtils.getInstance().getDate(end_date_string, "yyyy-MM-dd hh:mm"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			event.setEventUserIds(resource_id);
			event.setEventDetails(text);

			eventResponse.setAction(action);
			eventResponse.setTid(event.getEventId());
			eventResponse.setSid(ids);
			paramMap.put("eventResponse", eventResponse);
			getPlatformService().saveOrUpdateEvent(event);
		} else if (StringUtils.equalsIgnoreCase("updated", action)) {
			event.setUniqueKey(3);
			event.setEventId(ids);
			event.setEventLatitude(null);
			event.setEventName(ids);
			try {
				event.setEventStartDate(DateUtils.getInstance().getDate(start_date_string, "yyyy-MM-dd hh:mm"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				event.setEventEndDate(DateUtils.getInstance().getDate(end_date_string, "yyyy-MM-dd hh:mm"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			event.setEventUserIds(resource_id);
			event.setEventDetails(text);

			eventResponse.setAction(action);
			eventResponse.setTid(event.getEventId());
			eventResponse.setSid(ids);
			paramMap.put("eventResponse", eventResponse);
			getPlatformService().saveOrUpdateEvent(event);
		} else if (StringUtils.equalsIgnoreCase("deleted", action)) {
			event.setUniqueKey(3);
			event.setEventId(ids);
			event.setEventLatitude(null);
			event.setEventName(ids);
			try {
				event.setEventStartDate(DateUtils.getInstance().getDate(start_date_string, "yyyy-MM-dd hh:mm"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				event.setEventEndDate(DateUtils.getInstance().getDate(end_date_string, "yyyy-MM-dd hh:mm"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			event.setEventUserIds(resource_id);
			event.setEventDetails(text);

			eventResponse.setAction(action);
			eventResponse.setTid(event.getEventId());
			eventResponse.setSid(ids);
			paramMap.put("eventResponse", eventResponse);
			getPlatformService().deleteEvent(event);
		}

		return new ModelAndView("eventscheduler/action_response", paramMap);
	}

}
